import axios, { AxiosResponse } from 'axios';
import GlobalConfig from '../config/GlobalConfig';
import eventBus from './eventBus';
import { LocalStorageService } from './storage';

enum RequestType {
    get,
    post,
    put,
    delete
}


export class Ajax<T>{
    private url: string;
    private data?: object;
    private useSubHost: boolean = false;
    constructor(_url: string, _data?: object, _useSubHost: boolean = false) {
        this.url = _url;
        this.data = _data;
        this.useSubHost = _useSubHost;
    }

    public async get(): Promise<T> {
        let response: T;
        response = await this.request(RequestType.get)
        return response;
    }

    public async post(): Promise<T> {
        let response: T;
        response = await this.request(RequestType.post)
        return response;
    }

    public async put(): Promise<T> {
        let response: T;
        response = await this.request(RequestType.put)
        return response;
    }

    public async delete(): Promise<T> {
        let response: T;
        response = await this.request(RequestType.delete)
        return response;
    }

    private async request(type: RequestType): Promise<T> {
        let response: AxiosResponse<any>;
        let token: string = LocalStorageService.get('token');
        let requestConfig = {
            headers: {
                'content-type': "application/x-www-form-urlencoded; charset=UTF-8",
            }
        };
        let data = this.data || {};
        if (token) {
            data['token'] = token;
        }
        let httpUrl: string = (this.useSubHost ? GlobalConfig.subHost : GlobalConfig.host) + this.url;
        try {
            switch (type) {
                case RequestType.get:
                    response = await axios.get(`${httpUrl}?${this.paramsPostBody(data)}`, requestConfig);
                    break;
                case RequestType.post:
                    response = await axios.post(httpUrl, this.paramsPostBody(data), requestConfig);
                    break;
                case RequestType.put:
                    response = await axios.put(httpUrl, this.paramsPostBody(data), requestConfig);
                    break;
                case RequestType.delete:
                    response = await axios.delete(`${httpUrl}?${this.paramsPostBody(data)}`, requestConfig);
                    break;
            }
        } catch (e) {
            console.log("e", e);
            throw e;
        }
        let result = response.data;
        if (!this.useSubHost) {
            let status: number = result.status;
            if (status !== 1) {
                let error: string = result.error;
                if (error.indexOf("登录失效") > -1) {
                    eventBus.emit('logout');
                }
                throw error;
            }
            return result.data;
        } else {
            return result;
        }
    }

    private paramsPostBody(obj: any) {
        var result = '';//接受最后结果
        var item;
        for (item in obj) {
            result += '&' + item + '=' + encodeURIComponent(obj[item])
        }
        if (result) {
            result = result.slice(1)//去掉第一个&
        }
        return result
    }
}